package com.googlecode.ilstreets;

import java.io.ByteArrayOutputStream;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.codehaus.jackson.map.ObjectMapper;
import org.restlet.resource.Get;
import org.restlet.resource.Post;

import com.googlecode.ilstreets.persistent.Street;

public class StreetResource extends ParameterizedServerResource {
    
	@SuppressWarnings("unchecked")
	@Get("json")
    public Object doGet() {
    	if ((!params.containsKey("base")) || (!params.containsKey("city")))
    	{
    		return Collections.EMPTY_LIST;
    	}
    	
    	String base = params.get("base");
    	String city = params.get("city");
    	if ((base.length() == 0) && (city.length() == 0))
    	{
    		return Collections.EMPTY_LIST;
    	}

        PersistenceManager pm = PMF.get().getPersistenceManager();
        
        Query query = pm.newQuery(Street.class);
        query.setOrdering("name");
        query.setFilter("city == cityParam");
        query.declareParameters("String cityParam");
        List<Street> streets = Collections.EMPTY_LIST;
        try
        {
        	streets = (List<Street>)query.execute(city);
        } finally
        {
        	query.closeAll();
        }
        List<String> result = new LinkedList<String>();
        for (Street street : streets)
        {
        	if ((street.getName().startsWith(base))
        			|| (street.getName().indexOf(" "+base) > 0))
        	{
        		result.add(street.getName());
        	}
        }
        
        if (params.containsKey("callback"))
        {
        	String resultStr = "undefined";
        	
        	try
        	{
	        	ByteArrayOutputStream baos = new ByteArrayOutputStream();
        		ObjectMapper mapper = new ObjectMapper();
        		mapper.writeValue(baos, result);
	        	resultStr = baos.toString("UTF8");
        	} catch (Exception e) {
			}
        	
        	return params.get("callback")+"("+resultStr+");";
        }
        else
        {
        	return result;
        }
    }
	
	@Post
    public Object doPost() {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        pm.makePersistent(new Street(params.get("city"), params.get("street")));
        pm.close();
        return "Success";
	}
}
